package nl.infodation.emr.pricingservice.ui;

import java.util.ArrayList;
import java.util.List;

import nl.infodation.emr.pricingservice.controller.ControllerFactory;
import nl.infodation.emr.pricingservice.entity.SystemValue;
import nl.infodation.emr.pricingservice.entity.SystemValue.TableName;
import nl.infodation.emr.pricingservice.ui.component.ExplicitPagingContainer;
import nl.infodation.emr.pricingservice.ui.page.SessionData;
import nl.infodation.emr.utility.Constants;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vaadin.data.Item;
import com.vaadin.data.util.BeanItem;
import com.vaadin.data.util.ObjectProperty;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.Table;

@SuppressWarnings({ "unchecked", "rawtypes" })
public class CountryCheckerList extends Table {

	private static final String COL_COUNTRY_CODE = "systemCode";
	private static final String COL_CHOISE = "choise";
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory
			.getLogger(UserCountryCheckerList.class);
	final private ExplicitPagingContainer pagingContainer = new ExplicitPagingContainer();
	private final static List<String> activeList = new ArrayList<String>();

	public static List<String> getActiveList() {
		return activeList;
	}

	public Object[] STANDARD_COL_NAME;

	public String[] STANDARD_COL_HEADER;

	private void initColumnData() {
		STANDARD_COL_NAME = new Object[] { COL_CHOISE, COL_COUNTRY_CODE, };

		STANDARD_COL_HEADER = new String[] {
				SessionData.getI18N().getMessage(Constants.CHOISE_HEADER),
				SessionData.getI18N().getMessage(Constants.COUNTRY_CODE_HEADER) };
	}

	public CountryCheckerList() {
		clearActiveList();
		initColumnData();
		setSizeFull();
		initializePagingContainer();
		setPageSize(5);
		setContainerDataSource(pagingContainer);
		setVisibleColumns(STANDARD_COL_NAME);
		setColumnHeaders(STANDARD_COL_HEADER);
		setColumnCollapsingAllowed(true);
		setColumnReorderingAllowed(true);
		setColumnProperties();
		setSelectable(true);
		setImmediate(true);
		setNullSelectionAllowed(false);
		addGeneratedColumn();
		loadPage(1);
	}

	private void clearActiveList() {
		getActiveList().clear();
	}

	private void setColumnProperties() {
		setColumnWidth(COL_CHOISE, 50);
		setColumnAlignment(COL_CHOISE, Table.ALIGN_CENTER);
		setColumnWidth(COL_COUNTRY_CODE, 100);
		setColumnAlignment(COL_COUNTRY_CODE, Table.ALIGN_LEFT);
	}

	private void addGeneratedColumn() {
		addGeneratedColumn(COL_CHOISE, new BooleanColumnGenerator());
	}

	class BooleanColumnGenerator implements ColumnGenerator, ClickListener {

		private static final long serialVersionUID = 1L;

		public Object generateCell(Table source, Object itemId, Object columnId) {
			final BeanItem beanItem = (BeanItem) source.getItem(itemId);

			String debugId = null;
			String id = "";

			SystemValue c = (SystemValue) beanItem.getBean();
			debugId = c.getSystemCode();
			id = c.getSystemCode();

			final CheckBox chbChoise = new CheckBox("", false);

			ObjectProperty property = new ObjectProperty(false, Boolean.class);
			Item item = source.getItem(itemId);
			item.addItemProperty(columnId, property);

			chbChoise.setPropertyDataSource(property);
			chbChoise.setDebugId(debugId);
			chbChoise.setImmediate(true);
			chbChoise.addListener(this);

			// set value for checkbox
			if (CountryCheckerList.getActiveList().contains(id)) {
				property.setValue(true); // chkChoise is checked
			}

			return chbChoise;
		}

		@Override
		public void buttonClick(ClickEvent event) {
			final Button source = event.getButton();

			if (source instanceof CheckBox) {
				CheckBox box = (CheckBox) source;
				boolean enabled = event.getButton().booleanValue();
				try {
					String countryId = String.valueOf(box.getDebugId());
					activeList.remove(countryId);
					if (enabled) {
						activeList.add(countryId);
					}
				} catch (NumberFormatException numberFormatException) {
					LOG.debug("Failed parsing to Integer type",
							numberFormatException);
					LOG.error("Cann't stick/unstick the checkbox");
				}

			}
		}
	}

	private void initializePagingContainer() {
		pagingContainer.addContainerProperty(COL_CHOISE, Boolean.class, null);
		pagingContainer.addContainerProperty(COL_COUNTRY_CODE, String.class,
				null);
	}

	private void setPageSize(int size) {
		pagingContainer.setPageSize(size);
	}

	public void loadPage(int page) {
		List<BeanItem> items = new ArrayList<BeanItem>();

		if (SessionData.isSuperAdmin() || SessionData.isNormalAdmin()) {
			SystemValue systemValue = new SystemValue();
			systemValue.setSystemName(TableName.COUNTRY);
			items.addAll(ControllerFactory.getSystemValueController()
					.getPaginationByCriteria(systemValue, 1, Integer.MAX_VALUE));

		} else {
			for (SystemValue country : SessionData.getCountriesToSee()) {
				BeanItem item = new BeanItem(country);
				items.add(item);
			}
		}
		int beginIndex = (page - 1) * pagingContainer.getPageSize();
		int endIndex = beginIndex + pagingContainer.getPageSize();
		if (endIndex >= items.size()) {
			endIndex = items.size();
		}
		this.setDataSource(items.subList(beginIndex, endIndex));
	}

	public void reload() {
		loadPage(1);
	}

	public void setDataSource(final List<BeanItem> beans) {
		pagingContainer.setDataSource(beans);
	}

	public int getPageSize() {
		return pagingContainer.getPageSize();
	}

}
